package com.example.rabbitdemo.service;

import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 周宇
 * @version 1.0 date: 2019/7/23 11:19
 * @description:
 * @Copyright (C), 2017-2019, 深圳市⾦证引擎科技股份有限公司
 */
@Service
@Log4j2
public class SendService {
  /*//为了配合Return机制，我们要配置spring.rabbitmq.template.mandatory=true。
  // 它的作用是在消息没有被路由到合适的队列情况下，Broker会将消息返回给生产者.false则直接丢弃

  //消息发送到交换器Exchange后触发回调,需要开启publisher-confirms=true
  final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
      System.err.println("correlationData: " + correlationData);
      String messageId = correlationData.getId();
      if (b) {
        //如果confirm返回成功 则进行更新
        SendService.log.info("发送到交换机成功");
      } else {
        //失败则进行具体的后续操作:重试 或者补偿等手段
        SendService.log.error("发送到交换机失败");
      }
    }
  };
  // 如果消息从交换器发送到对应队列失败时触发，publisher-returns=true
  RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
    @Override
    public void returnedMessage(Message message, int replycode, String text, String exchange,
        String roukey) {
      SendService.log.error("消息没有投递到指定队列");
    }
  };*/

    @Autowired
    RabbitTemplate rabbitTemplate;

    public void sendDirectMsg() {
        //需要指定路由键
        rabbitTemplate.convertAndSend("Routing_Direct", "orange", "不喝奶茶的Programmer喜欢orange", new CorrelationData("orange"));
    }

    public void sendFanoutMsg() {
        //不需要指定路由键
        rabbitTemplate.convertAndSend("PS_fanoutExchange", null, "发布订阅模式");
    }

    void sendTopicMsg(){
        //指定路由键
        rabbitTemplate.convertAndSend("Exchange_Topic","a.orange.b","不喝奶茶的Programmer喜欢a.orange.b");
    }
}
